package a_sorting_basic.b_selection_sort_using_generics;

import a_sorting_basic.b_selection_sort_using_generics.sorting_helper.SortingHelperB;
import org.junit.Test;
import utils.ArrayGeneric;
import utils.Student;

@SuppressWarnings("unchecked")
public class SelectionSortUsingGenerics extends SortingHelperB {

    private void selectionSort(ArrayGeneric arr) {
        int len = arr.length();
        for (int i = 0; i < len; i++) {
            int minIndex = i;
            for (int j = i + 1; j < len; j++) {
                // find min index for current loop
                if (arr.get(j).compareTo(arr.get(minIndex)) < 0) {
                    minIndex = j;
                }
            }
            arr.swap(i, minIndex);
        }
    }

    @Test
    public void testing() {
        // 整数排序
        ArrayGeneric array = getRandomIntegerArray(10, 0, 30);
        selectionSort(array);
        // 字符串排序
        ArrayGeneric<String> arr2 = new ArrayGeneric<>(4);
        arr2.put(0, "pumpkin");
        arr2.put(1, "apple");
        arr2.put(2, "orange");
        arr2.put(3, "banana");
        selectionSort(arr2);
        // 对象排序
        ArrayGeneric<Student> arrStu = new ArrayGeneric<>(4);
        arrStu.put(0, new Student("delucia", 100));
        arrStu.put(1, new Student("james", 100));
        arrStu.put(2, new Student("woody", 97));
        arrStu.put(3, new Student("jack", 98));
        selectionSort(arrStu);
        // 性能测试
        ArrayGeneric tArrayGeneric = initSorting(50000);
        long start = System.nanoTime();
        executeSorting(tArrayGeneric);
        long end = System.nanoTime();
        System.out.println("用时 " + (end - start) / 1000000000.0);
    }

    @Test
    public void testSortingPerformance() {
        testSorting("selection sort", 50000);
        //时间复杂度 O = N^2
        //100          0.015
        //1000          0.030
        //10000         0.368
        //50000          11
        //100000        62.000
    }

    @Override
    public ArrayGeneric initSorting(int numbers) {
        return getRandomIntegerArray(numbers, 0, 1000);
    }

    @Override
    public void executeSorting(ArrayGeneric array) {
        selectionSort(array);
    }
}